package me.wangcai.onlinechat.manager;

import lombok.SneakyThrows;
import me.wangcai.onlinechat.model.User;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

public class UserManager {

    private static UserManager userManager;
    private Connection conn;

    private HashMap<User, HttpSession> userHttpSession = new HashMap<>();

    public static UserManager getUserManager() {
        if(userManager == null) userManager = new UserManager();
        return userManager;
    }

    @SneakyThrows
    private UserManager(){
        File file = new File(System.getProperty("user.dir") + "/database.db");
        System.out.println(file);
        if(!file.exists()) {
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager.getConnection("jdbc:sqlite://" + file);
        createTable();
    }

    @SneakyThrows
    public boolean register(String username, String password){
        PreparedStatement stat = conn.prepareStatement("INSERT INTO user VALUES (?,?)");
        stat.setString(1,username);
        stat.setString(2,password);
        stat.execute();
        stat.close();
        return true;
    }

    @SneakyThrows
    public boolean login(String username, String password){
        PreparedStatement stat = conn.prepareStatement("SELECT password from user WHERE username=?");
        stat.setString(1,username);
        ResultSet rs = stat.executeQuery();
        String password1 = rs.getString(1);
        rs.close();
        stat.close();
        return password.equals(password1);
    }

    @SneakyThrows
    public boolean isRegister(String username){
        PreparedStatement stat = conn.prepareStatement("SELECT count(*) FROM user WHERE username=?");
        stat.setString(1,username);
        ResultSet rs = stat.executeQuery();
        int amount = rs.getInt(1);
        stat.close();
        rs.close();
        return amount >= 1;
    }

    @SneakyThrows
    synchronized public void createTable(){
        PreparedStatement stat = conn.prepareStatement("CREATE TABLE  IF NOT EXISTS User(username TEXT PRIMARY KEY NOT NULL,password TEXT NOT NULL)");
        stat.execute();
        stat.close();
    }

    public HashMap<User, HttpSession> getUserHttpSession() {
        return userHttpSession;
    }
}
